package system1

import (
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/system1"
	system1Req "github.com/flipped-aurora/gin-vue-admin/server/model/system1/request"
	"gorm.io/gorm"
)

type WorkflowDefService struct {
}

// CreateWorkflowDef 创建审批流记录
// Author [piexlmax](https://github.com/piexlmax)
func (WorkflowService *WorkflowDefService) CreateWorkflowDef(Workflow *system1.WorkflowDef) (err error) {
	err = global.GVA_DB.Create(Workflow).Error
	return err
}

// DeleteWorkflowDef 删除审批流记录
// Author [piexlmax](https://github.com/piexlmax)
func (WorkflowService *WorkflowDefService) DeleteWorkflowDef(ID string, userID uint) (err error) {
	err = global.GVA_DB.Transaction(func(tx *gorm.DB) error {
		if err := tx.Model(&system1.WorkflowDef{}).Where("id = ?", ID).Update("deleted_by", userID).Error; err != nil {
			return err
		}
		if err = tx.Delete(&system1.WorkflowDef{}, "id = ?", ID).Error; err != nil {
			return err
		}
		return nil
	})
	return err
}

// DeleteWorkflowDefByIds 批量删除审批流记录
// Author [piexlmax](https://github.com/piexlmax)
func (WorkflowDefService *WorkflowDefService) DeleteWorkflowDefByIds(IDs []string, deleted_by uint) (err error) {
	err = global.GVA_DB.Transaction(func(tx *gorm.DB) error {
		if err := tx.Model(&system1.WorkflowDef{}).Where("id in ?", IDs).Update("deleted_by", deleted_by).Error; err != nil {
			return err
		}
		if err := tx.Where("id in ?", IDs).Delete(&system1.WorkflowDef{}).Error; err != nil {
			return err
		}
		return nil
	})
	return err
}

// UpdateWorkflowDef 更新审批流记录
// Author [piexlmax](https://github.com/piexlmax)
func (WorkflowService *WorkflowDefService) UpdateWorkflowDef(Workflow system1.WorkflowDef) (err error) {
	err = global.GVA_DB.Save(&Workflow).Error
	return err
}

// GetWorkflowDef 根据ID获取审批流记录
// Author [piexlmax](https://github.com/piexlmax)
func (WorkflowService *WorkflowDefService) GetWorkflowDef(ID string) (Workflow system1.WorkflowDef, err error) {
	err = global.GVA_DB.Where("id = ?", ID).First(&Workflow).Error
	return
}

// GetWorkflowDefInfoList 分页获取审批流记录
// Author [piexlmax](https://github.com/piexlmax)
func (WorkflowService *WorkflowDefService) GetWorkflowDefInfoList(info system1Req.WorkflowDefSearch) (list []system1.WorkflowDef, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&system1.WorkflowDef{})
	var Workflows []system1.WorkflowDef
	// 如果有条件搜索 下方会自动创建搜索语句
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}

	if limit != 0 {
		db = db.Limit(limit).Offset(offset)
	}

	err = db.Order("created_at DESC,updated_at DESC").Find(&Workflows).Error
	return Workflows, total, err
}
